package org.jtb.flickrportlet;

import java.net.URL;
import java.util.Collections;
import java.util.List;
import org.jtb.quickr.ContactsResponse.Contact;
import org.jtb.quickr.QuickrException;

public class ContactsBean {
    private List<Contact> contacts;
    private Contact selectedContact = null;
    private URL selectedContactBuddyIconUrl = null;
    
    public List<Contact> getContacts() {
        return Collections.unmodifiableList(contacts);
    }

    public void setContacts(List<Contact> contacts) throws QuickrException {
        this.contacts = contacts;
        if (contacts != null && contacts.size() > 0) {
            setSelectedContact(contacts.get(0).getNsId());
        }
    }
    
    
    public boolean isLoaded() {
        return contacts != null;
    }

    public Contact getSelectedContact() {
        return selectedContact;
    }
    
    public void setSelectedContact(String nsId) throws QuickrException {
        if (contacts == null || contacts.size() == 0) {
            throw new IllegalStateException("no contacts");
        }
        
        selectedContact = null;
        for (Contact c: contacts) {
            if (c.getNsId().equals(nsId)) {
                selectedContact = c;
                break;
            }
        }

        if (selectedContact == null) {
            throw new IllegalStateException("contact not found for nsid: " + nsId);
        }
        
        setSelectedContactBuddyIconUrl(selectedContact.getBuddyIconUrl());
    }

    public URL getSelectedContactBuddyIconUrl() {
        return selectedContactBuddyIconUrl;
    }

    public void setSelectedContactBuddyIconUrl(URL url) {
        this.selectedContactBuddyIconUrl = url;
    }
}
